import win32gui
import win32com.client
import win32gui
import win32api
import win32con
import win32ui
import os
import cv2 as cv

def query_handle_info() -> dict:
    hwnd_title = dict()
    def _get_all_hwnd(hwnd, mouse):
        if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
            hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})

    win32gui.EnumWindows(_get_all_hwnd, 0)
    return hwnd_title

def setForeground(hwnd):
    """
        将窗口设置为最前面
    :param hwnd: 窗口句柄 一个整数
    """
    if hwnd != win32gui.GetForegroundWindow():
        shell = win32com.client.Dispatch("WScript.Shell")
        shell.SendKeys('%')
        win32gui.SetForegroundWindow(hwnd)

# take the shot
def winShot(hwnd):
    bmpFileName = 'temp.bmp'

    r = win32gui.GetWindowRect(hwnd)
    hwin = win32gui.GetDesktopWindow()
    left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
    top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
    hwindc = win32gui.GetWindowDC(hwin)
    srcdc = win32ui.CreateDCFromHandle(hwindc)
    memdc = srcdc.CreateCompatibleDC()
    bmp = win32ui.CreateBitmap()
    bmp.CreateCompatibleBitmap(srcdc, r[2] - r[0], r[3] - r[1])
    memdc.SelectObject(bmp)
    memdc.BitBlt((-r[0], top - r[1]), (r[2], r[3] - top), srcdc, (left, top), win32con.SRCCOPY)
    bmp.SaveBitmapFile(memdc, bmpFileName)
    
    img = cv.imread(bmpFileName)
    cv.imshow('default',img)
    cv.waitKey(0)
    cv.destroyAllWindows()

    os.remove(bmpFileName)

if __name__ == '__main__':
    setForeground(66714)
    winShot(66714)
    info = query_handle_info()
